<?
class Connection extends Root{
	var $Session;		//Objet contenant la session PHP
	var $Num;		//Num de la connexion
	var $Date;		//Date de la connexion
	var $Ip;		//Ip de la connexio
	var $Host;		//Nom de l hote
	var $NavLang;		//Langue de l hote
	var $Navigateur;	//Type du navigateur
	var $Id;		//Id de connexion
	var $LastUrl;		//Derniere url html 
	var $FirstUrl;		//Premiere url html
	var $Utlisateur;	//id de l'utilisateur connecté
	var $Referent;		//Referent de la connexion
	var $Record;		//Object Connexion
	var $SessId="";
	var $login;
	var $pass;
	var $passmd5;
	var $codeverif;

	//------------------------------------------------------------//
	//			CONSTRUCTEUR			      //
	//------------------------------------------------------------//
	//C est ici que l on configure la connexion et que l on définit les processus d identification
	function Connection() {
		//Recherche de la connexion ou creatino si inexistante
 		$this->GetConn();
		//Detection de la langue
		$this->DetectLanguage();
		//On detecte l existence de cookies envoyés par le navigateur
		if ($this->DetectSessions()) {
			//Si l id de session est envoyé directement depuis un cookie alors on demarre la session
			//Sinon on charge les variables presentes dans le cookie
			if ($this->DetectAuth()) {
				//Demarrage Session
				$this->DemarreAuthSession();
				//Chargement des variables
				if (!$this->ChargementAuthVars())$this->LoadLoginVars();
				//Initialisation du usersession
				if (!$this->DetectUser()) $this->DestroyAuth();
				if($this->DetectSess()) $this->DestroySess();
			}elseif($this->DetectSess()){
				//Utilisateur public
				$this->initPublicSession();
				$this->LoadLoginVars();
				//Verficiation de la connexion
				if (!$this->DetectUser()){
				 	$this->initDefaultUser();
				}else{
					//Il faut basculer les informations de la session
					$this->SessionPublicToPrivate();
				}
			}
		}else{
			$this->LoadLoginVars();
			if ($this->DetectUser()) {
				//On genere l id de session
				$this->SessId = $this->genSessId($this->login,$this->pass,$this->Record->Id);
				//Creation Session
				$this->DemarreAuthSession();
				//Enregistrement des variable
				$this->SaveSessionVars();
			}else{
 				$this->initDefaultUser();
			}
		}
		//On enregistre la connexion
		if (is_object($this->Record)&&ADD_CONNECT){
			$this->Record->Set("Utilisateur",$GLOBALS["Systeme"]->User->Login);
			$this->Record->Save();
		}
	}

	//------------------------------------------------------------//
	//			SESSIONS DETECTION				      //
	//------------------------------------------------------------//

	function DetectSessions() {
		if ($this->DetectSess()||$this->DetectAuth()) return true ;else  return false;
	}
	function DetectSess() {
		$t=false;
		if ( $_COOKIE["PHPSESSID"]!="" ) {
			$this->SessId  = $_COOKIE["PHPSESSID"];
			$t=true;
		}
		if ( $_POST["PHPSESSID"]!="" ) {
			$this->SessId  = $_POST["PHPSESSID"];
			$t=true;
		}
		if ( $_GET["PHPSESSID"]!="" ) {
			$this->SessId  = $_GET["PHPSESSID"];
			$t=true;
		}
		if ($t) return true ;else  return false;
	}
	function DetectAuth() {
		if ( $_COOKIE["KE_SESSID"]!="" ) {
			$this->SessId  = $_COOKIE["KE_SESSID"];
			$t=true;
		}
		if ( $_POST["KE_SESSID"]!="" ) {
			$this->SessId  = $_POST["KE_SESSID"];
			$t=true;
		}
		if ( $_GET["KE_SESSID"]!="" ) {
			$this->SessId  = $_GET["KE_SESSID"];
			$t=true;
		}
		if ($t) return true ;else  return false;
	}

	//------------------------------------------------------------//
	//			SESSION AUTH			      //
	//------------------------------------------------------------//
	//Initialisation de la session prive
	function DemarreAuthSession() {
		//On recupere le numero de la session dans le cookie
		$Id = $this->extractSessId();
		$this->configAuthSession($Id);
		session_start();
	}
	//Extraction du numero de session depuis la session prive
	function extractSessId() {
		$temp = explode("dddd",$this->SessId);
		$Id = $temp[1];
		return $Id;
	}
	//Chargement des variables de la session prive
	function ChargementAuthVars() {
		if (!is_null($_SESSION["UserCache"]) && USER_CACHE){
			$GLOBALS["Systeme"]->User = unserialize($_SESSION["UserCache"]);
		}
		foreach ($_SESSION as $Key=>$Value){

			$GLOBALS["Systeme"]->RegisterVar($Key,(is_object(unserialize($Value))||is_array(unserialize($Value)))?unserialize($Value):$Value);
		}
		$this->login = $_SESSION["login"];
		$this->pass = $_SESSION["pass"];
		return true;
	}
	//Sauvegarde des variables de la session prive
	function SaveAuthVars() {
		$this->addSessionVar("login",$this->login);
		if (is_null($this->passmd5)) $this->addSessionVar("pass",$this->pass);
		else $this->addSessionVar("pass",$this->passmd5);
		$this->addSessionVar("UserCache",serialize($GLOBALS["Systeme"]->User));
	}
	//Configuratino de la session prive
	function ConfigAuthSession($Id) {
		session_set_cookie_params  (864000000);
		//Configuration de la session
		if ($Id==NULL) return false;
		session_name("KE_SESSID");
		//Emplacement de sauvegarde du fichier de session
		$Path = $_SERVER["DOCUMENT_ROOT"]."/Home/".$Id."/.sessions";
		if (!file_exists($Path)) $this->mk_dir($Path,0755);
		session_save_path($Path);
	}
	//Generation du numero de session prive
	function genSessId($login,$pass,$id) {
		$temp = md5($login."-".$pass);
		$temp = "dddd".$id."dddd".$temp;
		$sessid = $temp;
		session_id($sessid);
		return $sessid;
	}
	//Destruction de la session prive
	function DestroyAuth() {
		$GLOBALS["Systeme"]->isLogged=0;
		$_SESSION = array();
		if (isset($_COOKIE["KE_SESSID"])) {
			setcookie("KE_SESSID", '', time()-42000, '/');
		}
		$this->SessId = "";
		$this->Utilisateur = "";
		return true;
	}



	//------------------------------------------------------------//
	//			SESSION PHP			      //
	//------------------------------------------------------------//
	//Demarrage de la session publique
	function initPublicSession() {
	  	session_start();
		$this->ChargementSessionVars();
	}
	//Configuration de la session publique
	function ConfigPublicSession() {
		session_set_cookie_params  (864000000);
		//Configuration de la session
		session_name("PHPSESSID");
		//Emplacement de sauvegarde du fichier de session
		$Path = $_SERVER["DOCUMENT_ROOT"]."/Home/".$Id."/.sessions";
		if (!file_exists($Path)) $this->mk_dir($Path,0755);
		session_save_path($Path);
	}
	//Sauvegarde des variables de la session publique
	function SaveSessionVars() {
		$this->addSessionVar("login",$this->login);
		if (is_null($this->passmd5)) $this->addSessionVar("pass",$this->pass);
		else $this->addSessionVar("pass",$this->passmd5);
		$this->addSessionVar("UserCache",serialize($GLOBALS["Systeme"]->User));
	}
	//Chargement des variables de la session publique
	function ChargementSessionVars() {
		//On met les variables de session en variable globale
		if (!is_null($_SESSION["UserCache"]) && USER_CACHE){
			$GLOBALS["Systeme"]->User = unserialize($_SESSION["UserCache"]);
		}
//		if ($_SESSION["login"]=="")return false;
		foreach ($_SESSION as $Key=>$Value){

			$GLOBALS["Systeme"]->RegisterVar($Key,(is_object(unserialize($Value))||is_array(unserialize($Value)))?unserialize($Value):$Value);
		}
		$this->login = $_SESSION["login"];
		$this->pass = $_SESSION["pass"];
		return true;
	}
	//Transfert des variables de la session publique vers la session prive
	function SessionPublicToPrivate() {
		$OldSession = $_SESSION;
		$this->DestroySess();
		$this->SessId = $this->genSessId($this->login,$this->pass,$this->Record->Id);
		//Creation Session
		$this->DemarreAuthSession();
		$_SESSION = $OldSession;
		$this->SaveSessionVars();
	}
	//Destruction de la session prive
	function DestroySess() {
		if (isset($_COOKIE["PHPSESSID"])) {
			setcookie("PHPSESSID", '', time()-42000, '/');
		}
		return true;
	}
	//------------------------------------------------------------//
	//			VARIABLES KOB-EYE		      //
	//------------------------------------------------------------//
	//Ajoute une variable a la session
	function addSessionVar($Nom,$Valeur){
		session_register($Nom);
		$_SESSION[$Nom] = $Valeur;
		$GLOBALS["Systeme"]->RegisterVar($Nom,$Valeur);
	}
	//Supprime une variable de la session
	function rmSessionVar($Nom) {
		unset($_SESSION[$Nom]);
	}
	//Methode publique avec balise pour la gestion avec keml
	function Connect($Login,$Pass){
		$this->login = $Login;
		$this->pass = md5($Pass);
		if ($this->DetectUser() ){
			$this->SessionPublicToPrivate();
		}
	}
	//Recuperation des variables pouvant correspondre au login.
	function LoadLoginVars() {
		if ($GLOBALS["Systeme"]->getPostVars("login")!=""){
			//Ils sont dans les parametres Post
			$this->login = $GLOBALS["Systeme"]->getPostVars("login");
			$this->pass = md5($GLOBALS["Systeme"]->getPostVars("pass"));
			return true;
		}elseif ($GLOBALS["Systeme"]->getGetVars("login")!=""&&$GLOBALS["Systeme"]->getGetVars("passmd5")!=""&&$GLOBALS["Systeme"]->getGetVars("codeverif")!=""){
			$this->login = $GLOBALS["Systeme"]->getGetVars("login");
			$this->passmd5 = $GLOBALS["Systeme"]->getGetVars("passmd5");
			$this->codeverif = $GLOBALS["Systeme"]->getGetVars("codeverif");
			return true;
                }elseif ($_SESSION['login'] && $_SESSION['pass']){
                    	$this->login = $_SESSION['login'];
                        $this->pass = $_SESSION['pass'];
		}else{
			if ($this->login==""||$this->pass=="")	return false;
		}
	}

	//------------------------------------------------------------//
	//			CONNEXION			      //
	//------------------------------------------------------------//
	//Detection automatique de la langue
	function DetectLanguage() {
		//Detection automatique de la langue
		$Temp = $GLOBALS["Systeme"]->Conf->get("GENERAL::LANGUAGE");
		foreach ($Temp as $Tit=>$Lang){
			 if ($Lang["NAV"]=="*"&&$LangueSite==""){
				$LangueDefault=$Lang["TITLE"]; 
			}else {
				if (@preg_match("#^".$Lang["NAV"].".*$#",$this->Langue,$out)){
					$LangueSite = $Lang["TITLE"];
				}
			}
		}
		if ($LangueSite=="")$LangueSite = $LangueDefault;
		//Detection langue force
		if ($GLOBALS["Systeme"]->GetVars["SwitchLanguage"]!="") {
			//On verifie que l extension existe
			$Temp = $GLOBALS["Systeme"]->Conf->get("GENERAL::LANGUAGE");
			foreach ($Temp as $Tit=>$Lang) if ($Lang["TITLE"]==$GLOBALS["Systeme"]->GetVars["SwitchLanguage"]){
				$LangueSite = $GLOBALS["Systeme"]->GetVars["SwitchLanguage"];
			}
		}
		if ($this->Record->LangueSite!=""&&$this->Record->LangueSite!=$LangueDefault)$LangueSite=$this->Record->LangueSite;
		else $this->Record->LangueSite = $LangueSite;
		//Verification de la définition dans la connexion
		if ($LangueSite!="") $GLOBALS["Systeme"]->DefaultLanguage = $LangueSite;
	}

	//Recherche connexion
	function GetConn() {
		$GLOBALS["Chrono"]->start("GET Connexion");
		//Recuperation de l'id de session
		$this->DetectSess();
		$this->DetectAuth();
		//Recuperation de l adresse IP
		$this->Ip=getenv("REMOTE_ADDR");
		//Recuperation du nom de l hote
		$this->Host=gethostbyaddr(getenv("REMOTE_ADDR"));
		//Langage de l hote
		$this->Navigateur=str_replace("/","",utf8_decode(getenv("HTTP_USER_AGENT")));
		$this->Navigateur=str_replace("'","",$this->Navigateur);
		$this->Navigateur=str_replace('"',"",$this->Navigateur);
		$this->Navigateur=str_replace("&","",$this->Navigateur);
		$this->Navigateur=str_replace(";","",$this->Navigateur);
		$this->Navigateur=str_replace("+","",$this->Navigateur);
		$this->Navigateur=str_replace("=","",$this->Navigateur);
		$this->Navigateur=str_replace("`","",$this->Navigateur);
		$this->Navigateur=str_replace("{","",$this->Navigateur);
		$this->Navigateur=str_replace("}","",$this->Navigateur);
		$this->Navigateur=str_replace("(","",$this->Navigateur);
		$this->Navigateur=str_replace(")","",$this->Navigateur);
		$this->Navigateur=str_replace("[","",$this->Navigateur);
		$this->Navigateur=str_replace("]","",$this->Navigateur);
		$this->Navigateur = htmlspecialchars($this->Navigateur);
		$this->Ref = $_SERVER["HTTP_REFERER"];
		//Langage de l hote
		$this->Langue=getenv("HTTP_ACCEPT_LANGUAGE");
		//Generation de la date
		$this->Date = $this->initDate();
		//Recherche de la connexion
		if (ADD_CONNECT){
			$query="Systeme/Connexion/Langue=".$this->Langue."&Domaine=".$_SERVER["SERVER_NAME"]."&Navigateur=".addslashes($this->Navigateur)."&Ip=".$this->Ip."&tmsEdit>".(time()-(CONNECT_TIMEOUT*60));
			$Results = $GLOBALS['Systeme']->Modules['Systeme']->callData($query,false,0,1);
			if (!empty($Results[0])){
				//Connexion existante
				$this->Record = genericClass::createInstance("Systeme",$Results[0]);
			}else{
				//Creation de la connexion
				$this->Record = genericClass::createInstance("Systeme","Connexion");
				$this->Record->Set("Referent",$this->Ref);
				$this->Record->Set("FirstUrl",$_SERVER["REQUEST_URI"]);
				$this->Record->Set("Domaine",$_SERVER["SERVER_NAME"]);
				$this->Record->Set("Ip",$this->Ip);
				$this->Record->Set("Langue",$this->Langue);
				$this->Record->Set("Host",$this->Host);
				$this->Record->Set("Navigateur",$this->Navigateur);
			}
			//Configuration de la connexion
			$this->Record->Set("Session",$this->SessId);
			$this->Record->Set("LastUrl",$_SERVER["REQUEST_URI"]);
		}
		$GLOBALS["Chrono"]->stop("GET Connexion");
		return $Out;
	}

	function close () {
		if (ADD_CONNECT){
			//On supprime les connexions perimees
			$query="Systeme/Connexion/tmsEdit<".(time()-(CONNECT_TIMEOUT*60));
			$Results = $GLOBALS['Systeme']->Modules['Systeme']->callData($query);
			for ($i=0;$i<sizeof($Results);$i++) {
				$Connexion = genericClass::createInstance("Systeme","Connexion");
				$Connexion->Set("Id",$Results[$i]["Id"]);
				$Connexion->Delete();
			}
		}
	}

	//------------------------------------------------------------//
	//			USERS KOB-EYE			      //
	//------------------------------------------------------------//
	//Connexion d un utilisateur par un id ou par un tableau
	function initUser($Tab) {
		//Initialisation du genericClass
		if (is_object($Tab)) {
			//C est un objet
			$GLOBALS["Systeme"]->User = $Tab;
		}else{
			//C est un int
			$Result = $GLOBALS["Systeme"]->Modules["Systeme"]->callData("User/".$Tab);
			$User = genericClass::createInstance("Systeme",$Result[0]);
			$GLOBALS["Systeme"]->User = $User;
		}
		//Initialisation des groupes parents
		$Result = $GLOBALS["Systeme"]->Modules["Systeme"]->callData("Group/*/Group/User/".$GLOBALS["Systeme"]->User->Id);
		//Initialisation des genereicClass pour les groupes
		if (is_array($Result))foreach ($Result as $g) {
			$T[] = genericClass::createInstance("Systeme",$g);
		}
		$GLOBALS["Systeme"]->User->Groups = $T;
		//Definition de la skin
		if (is_array($GLOBALS["Systeme"]->User->Groups))foreach ($GLOBALS["Systeme"]->User->Groups as $g) {
			if ($g->Skin!=""&&$g->Skin) {
				$SkinGroup = $g->Skin;
			}
		}
		if ($GLOBALS["Systeme"]->User->Skin==""||$GLOBALS["Systeme"]->User->Skin=="0") $GLOBALS["Systeme"]->User->Skin = ($SkinGroup!=""&&$SkinGroup)?$SkinGroup:MAIN_SKIN_NUM;
		//Initialisation des menus
		$Menus = $GLOBALS["Systeme"]->Modules["Systeme"]->callData("Systeme/User/".$GLOBALS["Systeme"]->User->Id."/Menu/*");
		if (is_array($GLOBALS["Systeme"]->User->Groups))foreach ($GLOBALS["Systeme"]->User->Groups as $g) {
			$Mt = $GLOBALS["Systeme"]->Modules["Systeme"]->callData("Systeme/Group/".$g->Id."/Menu/*");
			if (is_array($Mt)&&sizeof($Mt)) {
				//On concatene les menus dans un seul tableau
				foreach ($Mt as $M) {
					$Menus[] = $M;
				}
			}
		}
		//Maintenant on reorganise les menus afin qu ils soient exploitables
		__autoload("Storproc");
		$Menus = StorProc::sortRecursivResult($Menus,"Menus");
                $Menus = $this->quickSort($Menus,"Ordre");
		//Initilisation des menus
		if (is_array($Menus))foreach ($Menus as $K=>$M) {
			$R[$K] = genericClass::createInstance("Systeme",$M);
			if (is_array($M["Menus"]))foreach ($M["Menus"] as $K2=>$M2) {
				$R[$K]->Menus[$K2] = genericClass::createInstance("Systeme",$M2);
				if (is_array($M2["Menus"]))foreach ($M2["Menus"] as $K3=>$M3) {
					$R[$K]->Menus[$K2]->Menus[$K3] = genericClass::createInstance("Systeme",$M3);
				}
			}
		}
		$GLOBALS["Systeme"]->User->Menus = $R;
		//Definition des acces par defaut
		//Home
		$A = genericClass::createInstance("Systeme","Access");
		$A->Set("Titre","Home");
		$A->Set("Requete","Home/".$GLOBALS["Systeme"]->User->Id);
		$Acces[] = $A;
		//Desktop
		$A = genericClass::createInstance("Systeme","Access");
		$A->Set("Titre","Desktop");
		$A->Set("Requete","Home/".$GLOBALS["Systeme"]->User->Id."/Desktop");
		$Acces[] = $A;
		//Public
		$A = genericClass::createInstance("Systeme","Access");
		$A->Set("Titre","Public");
		$A->Set("Requete","Home/Public");
		$Acces[] = $A;
		//Recherche des acces de l'utilisateur
		$Mt = $GLOBALS["Systeme"]->Modules["Systeme"]->callData("Systeme/User/".$GLOBALS["Systeme"]->User->Id."/Access");
		if (is_array($Mt)&&sizeof($Mt)) {
			//On concatene les acces dans un seul tableau
			foreach ($Mt as $M) {
				$Acces[] = genericClass::createInstance("Systeme",$M);
			}
		}
		//Recherche des acces des groupes parents
		if (is_array($GLOBALS["Systeme"]->User->Groups))foreach ($GLOBALS["Systeme"]->User->Groups as $g) {
			$Mt = $GLOBALS["Systeme"]->Modules["Systeme"]->callData("Systeme/Group/".$g->Id."/Access");
			if (is_array($Mt)&&sizeof($Mt)) {
				//On concatene les acces dans un seul tableau
				foreach ($Mt as $M) {
					$Acces[] = genericClass::createInstance("Systeme",$M);
				}
			}
		}
//  		print_r($GLOBALS["Systeme"]->User);
	}

	function DetectUser() {
		//Detection de l utilisateur
		if (!is_null($this->login)) {
			if (!is_null($this->passmd5)&&!is_null($this->codeverif)){
				//CAS LOGIN JETON MD5
				$Result = $GLOBALS["Systeme"]->Modules["Systeme"]->callData("User/Login=".$this->login."&Pass=".$this->passmd5."&CodeVerif=".$this->codeverif);
				$GLOBALS["Systeme"]->Log->log("DETECT USER >> PASSMD5 GET ".$Result[0]["Id"]);
				if (!is_array($Result[0])) return false;
				$User = genericClass::createInstance("Systeme",$Result[0]);
				$User->Save();
			}elseif (is_object($GLOBALS["Systeme"]->User) && !$GLOBALS["Systeme"]->User->Public){ 
				$GLOBALS["Systeme"]->Log->log("DETECT USER >> SESSION CACHE ".$GLOBALS["Systeme"]->User->Id);
				//CAS RECUP CACHE SESSION
				$User = $GLOBALS["Systeme"]->User;
				//$Result = $GLOBALS["Systeme"]->Modules["Systeme"]->callData("User/Login=".$User->Login."&Pass=".$User->Pass."&CodeVerif=".$User->CodeVerif);
				//if (!is_array($Result[0])) return false;
				//else 
				  return true;
			}
			else{
			  //				$GLOBALS["Systeme"]->Log->log("DETECT USER >> POST Login=".$this->login);
				//CAS LOGIN PASS POST
			        
				$Result = $GLOBALS["Systeme"]->Modules["Systeme"]->callData("User/Login=".$this->login."&Pass=".$this->pass);

				if (!is_array($Result[0])) return false;
				$User = genericClass::createInstance("Systeme",$Result[0]);
			}
			//On verifie le mot de passe dans  la classe generique
			if ($User->Actif) {
				$this->initUser($User);
				return true;
			}else{
				//OK donc il existe une session mais les dientifiants de connexion sont erron�s donc il faut detruire la session
// 				$GLOBALS["Systeme"]->Error->sendErrorMsg(100);
				$this->destroyAuth();
			}
		}
		return false;
	}

	function initDefaultUser() {
		$GLOBALS["Systeme"]->User = "";
		$GLOBALS["Chrono"]->start("INIT DEFAULT USER");
		//$Query,$recurs="",$Ofst="",$Limit="",$OrderType="",$OrderVar="",$Selection=""
		$Result = $GLOBALS["Systeme"]->Modules["Systeme"]->callData("Site/Domaine=".$_SERVER["HTTP_HOST"],false,0,1,"ASC","Id","m.Id,m.CodeVerif");
		if (is_array($Result[0])) {
			//On verifie quil nexiste pas deja un fichier cache pour lutilisateur
			//$User = genericClass::createInstance("Systeme",$Result[0]);
			if (USER_CACHE && $Result[0]["UserId"]>0 && file_exists("Home/".$Result[0]["UserId"]."/.UserCache")){
				$GLOBALS["Systeme"]->Log->log("DETECT USER >> LOAD CACHE DEFAULT USER DOMAINE ".$_SERVER["HTTP_HOST"]."  ".$User->Id);
				$GLOBALS["Systeme"]->User = unserialize(file_get_contents("Home/".$Result[0]["UserId"]."/.UserCache"));
				//if ($Result[0]["CodeVerif"]!=$GLOBALS["Systeme"]->User->CodeVerif&&$Result[0]["CodeVerif"]!="")$GLOBALS["Systeme"]->User = "";
			}
			if (!is_object($GLOBALS["Systeme"]->User)){
				$GLOBALS["Systeme"]->Log->log("DETECT USER >> INIT DEFAULT USER DOMAINE ".$_SERVER["HTTP_HOST"]."  ".$Result[0]["UserId"]);
				$this->initUser($Result[0]["UserId"]);
				//On genere le cache
				if (USER_CACHE)$this->writeCacheFile(serialize($GLOBALS["Systeme"]->User),"Home/".$Result[0]["UserId"]."",".UserCache");
			}
		}else{
                    
			if (file_exists("Home/".MAIN_USER_NUM."/.UserCache") && USER_CACHE){
				$GLOBALS["Systeme"]->Log->log("DETECT USER >> LOAD CACHE DEFAULT USER MAIN_USER_NUM ".MAIN_USER_NUM);
				$GLOBALS["Systeme"]->User = unserialize(file_get_contents("Home/".MAIN_USER_NUM."/.UserCache"));
				if ($Result[0]["CodeVerif"]->CodeVerif!=$GLOBALS["Systeme"]->User->CodeVerif&&$Result[0]["CodeVerif"]!="")$GLOBALS["Systeme"]->User = "";
			}
			if (!is_object($GLOBALS["Systeme"]->User)){
				$GLOBALS["Systeme"]->Log->log("DETECT USER >> INIT DEFAULT USER MAIN_USER_NUM ".MAIN_USER_NUM);
				$this->initUser(MAIN_USER_NUM);
				//On genere le cache
				$this->writeCacheFile(serialize($GLOBALS["Systeme"]->User),"Home/".MAIN_USER_NUM."",".UserCache");
			}
 		}
		$GLOBALS["Chrono"]->stop("INIT DEFAULT USER");
		$GLOBALS["Systeme"]->User->Public = 1;
	}

	function writeCacheFile($Data,$Url,$Name) {
		$GLOBALS["Systeme"]->Log->log("CACHE >> WRITE CACHE  ".$Url."/".$Name);
		if (!$File=fopen ($Url."/".$Name,"w")){
			$this->mk_dir($Url);
		}
		fwrite($File,$Data);
		fclose($File);
	}

	function isLogged() {
		if ($this->SessId!="") return true;
		else return false;
	}
	//Deconnexion sans redirection
	function DisconnectInPlace(){
		$GLOBALS["Systeme"]->isLogged=0;
		if ($this->DetectSess()) $this->DestroySess();
		if ($this->DetectAuth()) $this->DestroyAuth();
		return;
	}
	//Deconnexino et redirection vers l'accueil
	function Disconnect() {
		$GLOBALS["Systeme"]->isLogged=0;
		if ($this->DetectSess()) $this->DestroySess();
		if ($this->DetectAuth()) $this->DestroyAuth();
		header("Location: http://".$_SERVER["HTTP_HOST"]."/");
		return;
	}

	//------------------------------------------------------------//
	//			UTILS				      //
	//------------------------------------------------------------//

	function initDate() {
	//Fonction d initialisation de la date
		$TempDate=date("YmdHis");
		return $TempDate;
	}

	function mk_dir($path, $rights = 0777){
		$folder_path = array($path);
		while(!@is_dir(dirname(end($folder_path)))
			&& dirname(end($folder_path)) != '/'
			&& dirname(end($folder_path)) != '.'
			&& dirname(end($folder_path)) != '')
		array_push($folder_path, dirname(end($folder_path)));
		while($parent_folder_path = array_pop($folder_path)){
			if(@mkdir($parent_folder_path, $rights))
			//user_error("Can't create folder \"$parent_folder_path\".");
			chmod ($parent_folder_path,$rights);
		}
	}
	



}




?>
